package org.ponly.cta4j.factory.math;

import java.awt.image.BufferedImage;
import org.ponly.cta4j.factory.AbstractCaptcha;

/**
 * 数学计算验证码.
 *
 * @author vacoor
 * @since 1.0
 */
public class MathCaptcha extends AbstractCaptcha {
    /**
     * Response.
     */
    private final int response;

    /**
     * 创建一个数学验证码.
     *
     * @param challenge 验证码图片
     * @param response  response
     */
    MathCaptcha(final BufferedImage challenge, final int response) {
        super(challenge);
        this.response = response;
    }

    /**
     * @return response
     */
    public int getResponse() {
        return response;
    }

    @Override
    public boolean validate(final Object response) {
        if (response instanceof Number) {
            return getResponse() == ((Number) response).intValue();
        }
        if (response instanceof String) {
            try {
                return getResponse() == Integer.valueOf((String) response, 10);
            } catch (final NumberFormatException ex) {
                // ignore
            }
        }
        return false;
    }
}
